import router from '@/router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import ACCESS_ENUM from '@/access/accessEnum.ts'
import checkAccess from '@/access/checkAccess.ts'


router.beforeEach(async (to, from, next) => {
  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser
  console.log('登录用户信息',loginUser)
  const needAccess = (to.meta?.access as string)??ACCESS_ENUM.NOT_LOGIN
  if (!loginUser|| !loginUser.userRole) { //如果未登录，则获取用户信息
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
  }
  //要跳转的页面必须登录
  if(needAccess !== ACCESS_ENUM.NOT_LOGIN){
    if (!loginUser ||!loginUser.userRole || loginUser.userRole === ACCESS_ENUM.NOT_LOGIN) {
      next('/user/login?redirect=${to.fullPath}')
      return
    }
    //已登录但无权限的跳到无权限界面
    if(!checkAccess(loginUser,needAccess)){
      next('/noAuth')
      return
    }
  }
  next()
})
